package com.yj.auto.core.web.system.controller;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Model;
import com.xiaoleilu.hutool.crypto.SecureUtil;
import com.yj.auto.Constants;
import com.yj.auto.core.base.annotation.Controller;
import com.yj.auto.core.base.annotation.Valid;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.base.model.ResponseModel;
import com.yj.auto.core.jfinal.base.BaseController;
import com.yj.auto.core.web.system.model.Org;
import com.yj.auto.core.web.system.model.User;
import com.yj.auto.core.web.system.model.UserRole;
import com.yj.auto.core.web.system.model.validator.UserEditGroup;
import com.yj.auto.core.web.system.model.validator.UserSetGroup;
import com.yj.auto.core.web.system.service.OrgService;
import com.yj.auto.core.web.system.service.UserService;
import com.yj.auto.helper.AutoHelper;
import com.yj.auto.plugin.table.model.DataTables;
import com.yj.auto.plugin.ztree.ZTreeNode;

/**
 * 系统用户 管理
 * 
 * 描述：
 * 
 */
@Controller(viewPath = "system")
public class UserController extends BaseController {
	private static final Log logger = Log.getLog(UserController.class);

	private static final String RESOURCE_URI = "user/index";
	private static final String INDEX_PAGE = "user_index.html";
	private static final String FORM_PAGE = "user_form.html";
	private static final String SHOW_PAGE = "user_show.html";
	private static final String SET_PAGE = "user_set.html";
	UserService userSrv = null;

	public void index() {
		render(INDEX_PAGE);
	}

	public void list(QueryModel query) {
		DataTables<User> dt = getDataTable(query, userSrv);
		renderJson(dt);
	}

	public void get() {
		Integer id = getParaToInt(0);
		User model = userSrv.get(id);
		if (StrKit.notNull(model.getId())) {
			model.setOrg(AutoHelper.getOrgService().get(model.getOrgId()));
		}
		setAttr("model", model);
		render(SHOW_PAGE);
	}

	public void form() {
		Integer id = getParaToInt(0);
		User model = null;
		if (null != id && 0 != id) {
			model = userSrv.get(id);
			if (StrKit.notNull(model.getOrgId())) {
				model.setOrg(AutoHelper.getOrgService().get(model.getOrgId()));
			}
			model.setPwd(null);
		} else {
			model = new User();
			model.setSort(Constants.MODEL_SORT_DEFAULT);
			model.setPwd(Constants.DEFAULT_PASSWORD);// 默认密码
		}
		setAttr("model", model);
		setAttr("roles", userSrv.findAllRoles(model.getId()));
		render(FORM_PAGE);
	}

	@Valid(type = User.class, groups = { UserEditGroup.class, UserSetGroup.class })
	public boolean saveOrUpdate(User model) {
		List<UserRole> roles = new ArrayList<UserRole>();
		Integer[] items = getParaValuesToInt("userRoles");
		if (null != items) {
			for (Integer id : items) {
				UserRole rr = new UserRole();
				rr.setRoleId(id);
				roles.add(rr);
			}
		}
		model.setRoles(roles);

		model.setLuser(getSuId());
		model.setLtime(Constants.NOW());

		if (StrKit.isBlank(model.getPwd())) {
			model.setPwd(Constants.DEFAULT_PASSWORD);// 默认密码
		}

		boolean success = false;
		if (null == model.getId()) {
			if (null != userSrv.getByCode(model.getCode())) {
				ResponseModel<String> res = new ResponseModel<String>(false);
				res.setMsg("登录账号[" + model.getCode() + "]已存在!");
				renderJson(res);
				return false;
			}
			model.setPwd(SecureUtil.md5(model.getPwd()));// MD5
			success = userSrv.save(model);
		} else {
			if (getParaToBoolean("updatePwd")) {
				model.setPwd(SecureUtil.md5(model.getPwd()));// MD5
			} else {// 无需更改密码
				model.remove("pwd");
			}
			success = userSrv.update(model);
		}
		ResponseModel<String> res = renderSaveOrUpdate(success, userSrv);
		return res.isSuccess();
	}

	public void set() {
		User model = userSrv.get(this.getSuId());
		setAttr("model", model);
		render(SET_PAGE);
	}

	@Valid(type = User.class, groups = { UserSetGroup.class })
	public boolean updateSet(User model) {
		model.setLuser(getSuId());
		model.setLtime(Constants.NOW());
		model.setId(getSuId());
		boolean success = false;
		if ("true".equals(getPara("updatePwd"))) {
			String pwd = SecureUtil.md5(getPara("old_pwd"));// 当前密码 MD5
			if (null == pwd || !pwd.equals(userSrv.get(model.getId()).getPwd())) {
				ResponseModel<String> res = new ResponseModel<String>(success);
				res.setMsg("当前密码错误");
				renderJson(res);
				return success;
			}
			model.setPwd(SecureUtil.md5(model.getPwd()));
		} else {// 无需更改密码
			model.remove("pwd");
		}
		initAttaMap(model, UserService.ATTA_USER_PHOTO);// 获取用户头像
		success = userSrv.update(model);
		ResponseModel<String> res = renderSaveOrUpdate(success, userSrv);
		return success;
	}

	public boolean delete() {
		ResponseModel<String> res = _delete(userSrv);
		return res.isSuccess();
	}

	public void children() {
		OrgService orgSrv = AutoHelper.getOrgService();
		Integer id = null;
		String param = getPara("id");
		if (StrKit.notBlank(param)) {
			id = Integer.parseInt(param.substring(1));
		}
		List<Org> list = orgSrv.children(id, Constants.DATA_STATE_VALID);
		List<ZTreeNode> result = new ArrayList<ZTreeNode>();
		for (Org root : list) {
			List<Org> subs = orgSrv.children(root.getId(), Constants.DATA_STATE_VALID);
			List<User> users = userSrv.findByDept(root.getId(), Constants.DATA_STATE_VALID);
			ZTreeNode t = getZTreeNode(root, (subs.size() + users.size()) > 0, "org");
			if (null == id && t.getIsParent()) {
				t.setOpen(true);
				for (Org obj : subs) {
					ZTreeNode st = getZTreeNode(obj, orgSrv.children(obj.getId(), Constants.DATA_STATE_VALID).size() > 0, "org");
					t.addChildren(st);
				}
				for (User obj : users) {
					ZTreeNode st = getZTreeNode(obj, false, "user");
					t.addChildren(st);
				}
			}
			result.add(t);
		}
		renderJson(result);
	}

	private ZTreeNode getZTreeNode(Model model, boolean parent, String type) {
		ZTreeNode t = new ZTreeNode(model.getStr("id"), model.getStr("name"));
		if ("org".equals(type)) {// 机构，不允许选择
			t.setNocheck(true);
			t.setId("O" + t.getId());
		} else {// 用户
			t.setNocheck(false);
			t.setId("U" + t.getId());
		}
		t.setIsParent(parent);
		return t;
	}
}